<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>接口测试</el-breadcrumb-item>
      <el-breadcrumb-item>公共配置</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片-->
    <el-card class="box-card">
      <el-row :gutter="20">
        <!--搜索框-->
        <el-col :span="6">
          <el-input placeholder="请输入公共配置名称" v-model="queryParams.name" clearable @clear="getConfigList" @keyup.enter.native="getConfigList">
            <el-button slot="append" icon="el-icon-search" @click="getConfigList" class="search"></el-button>
          </el-input>
        </el-col>
        <!--创建按钮-->
        <el-col :span="4">
          <el-button type="primary" @click="openAddConfigDialog" plain>创建公共配置</el-button>
        </el-col>
      </el-row>
      <!--表格-->
      <el-table :data="configList" :cell-style="cellStyle" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="公共配置名称" prop="name"></el-table-column>
        <el-table-column label="所属接口" prop="interface"></el-table-column>
        <el-table-column label="创建时间" prop="create_time"></el-table-column>
        <el-table-column label="操作" min-width="77px">
          <template slot-scope="scope">
            <el-button type="warning" size="mini" @click="openEditConfigDialog(scope.row)" plain>编 辑</el-button>
            <el-button type="danger" size="mini" @click="deleteThisConfig(scope.row.id)" plain>删 除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.p"
        :page-sizes="[5, 10, 20, 40]"
        :page-size="queryParams.s"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--新建公共配置对话框-->
    <el-dialog title="创建公共配置" :visible.sync="addConfigDialogVisible" width="56%" :append-to-body="true"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="addDialogClose">
      <!--公共配置表单-->
      <el-form :model="addConfigForm" status-icon :rules="addConfigRule" ref="addConfigRef" label-width="90px">
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="addConfigForm.project_id" placeholder="请选择所属项目"  @change="addProjectChange">
            <el-option
              v-for="project in projectAndInterfaceNames"
              :key="project.id"
              :label="project.name"
              :value="project.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属接口" prop="interface_id">
          <el-select v-model="addConfigForm.interface_id" placeholder="请选择所属接口">
            <el-option
              v-for="interface1 in interfaceNames"
              :key="interface1.id"
              :label="interface1.name"
              :value="interface1.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="addConfigForm.name" placeholder="请输入公共配置名称"></el-input>
        </el-form-item>
        <el-tabs v-model="activeName" @tab-click="handleTabPage">
          <el-tab-pane label="公共请求头" name="first">
            <el-row :gutter="20" v-for="(header, index) in headerList" :key="index">
              <el-col :span="8">
                <el-input v-model="header.key" placeholder="key" size="mini"></el-input>
              </el-col>
              <el-col :span="14">
                <el-input v-model="header.value" placeholder="value" size="mini"></el-input>
              </el-col>
              <el-col :span="2">
                <el-button @click="deleteHeader(header)" icon="el-icon-delete" size="mini"></el-button>
              </el-col>
            </el-row>
            <el-row style="text-align: right; margin-right: 13px">
              <el-button @click="addHeader" icon="el-icon-plus" size="mini"></el-button>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="全局变量" name="second">
            <el-row :gutter="20" v-for="(variable, index) in variableList" :key="index">
              <el-col :span="6">
                <el-input v-model="variable.key" placeholder="key" size="mini"></el-input>
              </el-col>
              <el-col :span="3">
                <el-select v-model="variable.type" placeholder="type" size="mini">
                  <el-option
                    v-for="item in dataType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="13">
                <el-input v-model="variable.value" placeholder="value" size="mini"></el-input>
              </el-col>
              <el-col :span="2">
                <el-button @click="deleteVariable(variable)" icon="el-icon-delete" size="mini"></el-button>
              </el-col>
            </el-row>
            <el-row style="text-align: right; margin-right: 13px">
              <el-button @click="addVariable" icon="el-icon-plus" size="mini"></el-button>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addConfigDialogClose">取 消</el-button>
        <el-button type="primary" @click="addConfig">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑公共配置对话框-->
    <el-dialog title="编辑公共配置" :visible.sync="editConfigDialogVisible" width="56%" :append-to-body="true"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="editDialogClose">
      <!--公共配置表单-->
      <el-form :model="editConfigForm" status-icon :rules="editConfigRule" ref="editConfigRef" label-width="90px">
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="editConfigForm.project_id" placeholder="请选择所属项目" @change="editProjectChange">
            <el-option
              v-for="project in projectAndInterfaceNames"
              :key="project.id"
              :label="project.name"
              :value="project.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属接口" prop="interface_id">
          <el-select v-model="editConfigForm.interface_id" placeholder="请选择所属接口">
            <el-option
              v-for="interface1 in interfaceNames"
              :key="interface1.id"
              :label="interface1.name"
              :value="interface1.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="editConfigForm.name" placeholder="请输入公共配置名称"></el-input>
        </el-form-item>
        <el-tabs v-model="activeName" @tab-click="handleTabPage">
          <el-tab-pane label="公共请求头" name="first">
            <el-row :gutter="20" v-for="(header, index) in headerList" :key="index">
              <el-col :span="8">
                <el-input v-model="header.key" placeholder="key" size="mini"></el-input>
              </el-col>
              <el-col :span="14">
                <el-input v-model="header.value" placeholder="value" size="mini"></el-input>
              </el-col>
              <el-col :span="2">
                <el-button @click="deleteHeader(header)" icon="el-icon-delete" size="mini"></el-button>
              </el-col>
            </el-row>
            <el-row style="text-align: right; margin-right: 13px">
              <el-button @click="addHeader" icon="el-icon-plus" size="mini"></el-button>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="全局变量" name="second">
            <el-row :gutter="20" v-for="(variable, index) in variableList" :key="index">
              <el-col :span="6">
                <el-input v-model="variable.key" placeholder="key" size="mini"></el-input>
              </el-col>
              <el-col :span="3">
                <el-select v-model="variable.type" placeholder="type" size="mini">
                  <el-option
                    v-for="item in dataType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="13">
                <el-input v-model="variable.value" placeholder="value" size="mini"></el-input>
              </el-col>
              <el-col :span="2">
                <el-button @click="deleteVariable(variable)" icon="el-icon-delete" size="mini"></el-button>
              </el-col>
            </el-row>
            <el-row style="text-align: right; margin-right: 13px">
              <el-button @click="addVariable" icon="el-icon-plus" size="mini"></el-button>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editConfigDialogClose">取 消</el-button>
        <el-button type="primary" @click="editThisConfig">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getProjectAndInterfaceNames, getConfigs, createConfig, editConfig, deleteConfig } from '../../api/api'

export default {
  created () {
    this.getConfigList()
    this.getProjectAndInterfaceNameList()
  },
  data () {
    return {
      configList: [],
      queryParams: {
        p: 1,
        s: 10,
        name: ''
      },
      tmpName: '',
      dataType: [
        { value: 1, label: 'string' },
        { value: 2, label: 'int' },
        { value: 3, label: 'float' },
        { value: 4, label: 'boolean' }
      ],
      projectAndInterfaceNames: [],
      interfaceNames: [],
      total: 0,
      addConfigDialogVisible: false,
      addConfigForm: {
        project_id: '',
        interface_id: '',
        name: '',
        content: {
          headers: {},
          variables: []
        }
      },
      activeName: 'first',
      editConfigDialogVisible: false,
      configId: '',
      editConfigForm: {},
      headerList: [{
        key: '',
        value: ''
      }],
      variableList: [{
        key: '',
        type: 'string',
        value: ''
      }],
      tmpList: [],
      tmpDict: {},
      addConfigRule: {
        project_id: [
          { required: true, message: '所属项目不能为空！', trigger: 'blur' }
        ],
        interface_id: [
          { required: true, message: '所属接口不能为空！', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '公共配置名称不能为空！', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符！', trigger: 'blur' }
        ]
      },
      editConfigRule: {
        project_id: [
          { required: true, message: '所属项目不能为空！', trigger: 'blur' }
        ],
        interface_id: [
          { required: true, message: '所属接口不能为空！', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '公共配置名称不能为空！', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符！', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取公共配置列表
    getConfigList () {
      if (this.queryParams.name !== this.tmpName) {
        this.tmpName = this.queryParams.name
        this.queryParams.p = 1
      }
      getConfigs(this.queryParams)
        .then(response => {
          if (response.data.code !== 0) return this.$message.error('获取公共配置列表失败！')
          this.configList = response.data.data.results
          this.total = response.data.data.count
        })
    },
    // 获取项目和接口名称列表
    getProjectAndInterfaceNameList () {
      getProjectAndInterfaceNames()
        .then(response => {
          if (response.data.code !== 0) return this.$message.error('获取项目名称列表失败！')
          this.projectAndInterfaceNames = response.data.data
          for (const project of this.projectAndInterfaceNames) {
            if (project.id === this.editConfigForm.project_id) {
              this.interfaceNames = project.interface
            }
          }
        })
    },
    // 获取创建公共配置项目下的接口
    addProjectChange () {
      for (const project of this.projectAndInterfaceNames) {
        if (project.id === this.addConfigForm.project_id) {
          this.interfaceNames = project.interface
          if (this.interfaceNames.length > 0) {
            this.addConfigForm.interface_id = this.interfaceNames[0].id
          } else {
            this.addConfigForm.interface_id = null
          }
        }
      }
    },
    // 获取编辑公共配置项目下的接口
    editProjectChange () {
      for (const project of this.projectAndInterfaceNames) {
        if (project.id === this.editConfigForm.project_id) {
          this.interfaceNames = project.interface
          if (this.interfaceNames.length > 0) {
            this.editConfigForm.interface_id = this.interfaceNames[0].id
          } else {
            this.editConfigForm.interface_id = null
          }
        }
      }
    },
    // 打开创建公共配置对话框
    openAddConfigDialog () {
      this.getProjectAndInterfaceNameList()
      this.headerList = [{ key: '', value: '' }]
      this.variableList = [{ key: '', type: 'string', value: '' }]
      this.addConfigForm.content = {}
      this.addConfigDialogVisible = true
    },
    handleTabPage (tab, event) {
      return 0
    },
    // 新增公共请求头表单项
    addHeader () {
      this.headerList.push({
        key: '',
        value: ''
      })
    },
    // 新增全局变量表单项
    addVariable () {
      this.variableList.push({
        key: '',
        type: 'string',
        value: ''
      })
    },
    // 删除公共请求头表单项
    deleteHeader (item) {
      const index = this.headerList.indexOf(item)
      if (index !== -1 && this.headerList.length > 1) {
        this.headerList.splice(index, 1)
      }
    },
    // 删除全局变量表单项
    deleteVariable (item) {
      const index = this.variableList.indexOf(item)
      if (index !== -1 && this.variableList.length > 1) {
        this.variableList.splice(index, 1)
      }
    },
    // 创建公共配置
    addConfig () {
      this.addConfigForm.content = {}
      // 移除多余的请求头空白项
      this.tmpList = this.headerList
      this.headerList = []
      for (const header of this.tmpList) {
        if (header.key !== '' && header.value !== '') {
          this.headerList.push(header)
        }
      }
      if (this.headerList.length === 0) {
        this.addHeader()
      }
      if (this.headerList.length === 1 && this.headerList[0].key === '' && this.headerList[0].value === '') {
        this.addConfigForm.content.headers = {}
      } else {
        this.addConfigForm.content.headers = {}
        for (const header of this.headerList) {
          this.addConfigForm.content.headers[header.key] = header.value
        }
      }
      // 移除多余的全局变量空白项
      this.tmpList = this.variableList
      this.variableList = []
      for (const variable of this.tmpList) {
        if (variable.key !== '') {
          this.variableList.push(variable)
        }
      }
      if (this.variableList.length === 0) {
        this.addVariable()
      }
      if (this.variableList.length === 1 && this.variableList[0].key === '' && this.variableList[0].value === '') {
        this.addConfigForm.content.variables = []
      } else {
        this.addConfigForm.content.variables = this.variableList
      }
      this.addConfigForm.content = JSON.stringify(this.addConfigForm.content)
      this.$refs.addConfigRef.validate(valid => {
        if (!valid) return
        createConfig(this.addConfigForm)
          .then(response => {
            if (response.data.code !== 0) return this.$message.error('创建公共配置失败！')
            this.$message.success('创建公共配置成功！')
            this.addConfigDialogClose()
            this.getConfigList()
          })
      })
    },
    // 创建对话框关闭
    addDialogClose () {
      this.$refs.addConfigRef.resetFields()
      this.interfaceNames = []
      this.addConfigForm = {
        project_id: '',
        interface_id: '',
        name: '',
        content: {
          headers: {},
          variables: []
        }
      }
      this.activeName = 'first'
    },
    // 创建公共配置对话框关闭
    addConfigDialogClose () {
      this.addConfigDialogVisible = false
      this.addDialogClose()
    },
    // 打开编辑公共配置对话框
    openEditConfigDialog (configInfo) {
      this.getProjectAndInterfaceNameList()
      this.editConfigForm = { ...configInfo }
      this.configId = this.editConfigForm.id
      delete this.editConfigForm.id
      delete this.editConfigForm.interface
      delete this.editConfigForm.create_time
      this.editConfigForm.content = JSON.parse(this.editConfigForm.content)
      if (Object.keys(this.editConfigForm.content.headers).length === 0) {
        this.headerList = [{ key: '', value: '' }]
      } else {
        this.headerList = []
        for (const key in this.editConfigForm.content.headers) {
          this.headerList.push({
            key: key,
            value: this.editConfigForm.content.headers[key]
          })
        }
      }
      if (Object.keys(this.editConfigForm.content.variables).length === 0) {
        this.variableList = [{ key: '', type: 'string', value: '' }]
      } else {
        this.variableList = []
        for (const variable of this.editConfigForm.content.variables) {
          this.variableList.push({
            key: variable.key,
            type: variable.type,
            value: variable.value
          })
        }
      }
      this.editConfigDialogVisible = true
    },
    // 编辑这个公共配置
    editThisConfig () {
      this.editConfigForm.content = {}
      // 移除多余的请求头空白项
      this.tmpList = this.headerList
      this.headerList = []
      for (const header of this.tmpList) {
        if (header.key !== '' && header.value !== '') {
          this.headerList.push(header)
        }
      }
      if (this.headerList.length === 0) {
        this.addHeader()
      }
      if (this.headerList.length === 1 && this.headerList[0].key === '' && this.headerList[0].value === '') {
        this.editConfigForm.content.headers = {}
      } else {
        this.editConfigForm.content.headers = {}
        for (const header of this.headerList) {
          this.editConfigForm.content.headers[header.key] = header.value
        }
      }
      // 移除多余的全局变量空白项
      this.tmpList = this.variableList
      this.variableList = []
      for (const variable of this.tmpList) {
        if (variable.key !== '') {
          this.variableList.push(variable)
        }
      }
      if (this.variableList.length === 0) {
        this.addVariable()
      }
      if (this.variableList.length === 1 && this.variableList[0].key === '' && this.variableList[0].value === '') {
        this.editConfigForm.content.variables = []
      } else {
        this.editConfigForm.content.variables = this.variableList
      }
      this.editConfigForm.content = JSON.stringify(this.editConfigForm.content)
      this.$refs.editConfigRef.validate(valid => {
        if (!valid) return
        editConfig(this.configId, this.editConfigForm)
          .then(response => {
            if (response.data.code !== 0) return this.$message.error('编辑公共配置失败！')
            this.$message.success('编辑公共配置成功！')
            this.editConfigDialogClose()
            this.getConfigList()
          })
      })
    },
    // 编辑对话框关闭
    editDialogClose () {
      this.$refs.editConfigRef.resetFields()
      this.activeName = 'first'
    },
    // 编辑公共配置对话框关闭
    editConfigDialogClose () {
      this.editConfigDialogVisible = false
      this.editDialogClose()
    },
    // 删除公共配置
    deleteThisConfig (configId) {
      this.$confirm('此操作将永久删除该公共配置, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteConfig(configId).then(response => {
          if (response.data.code !== 0) return this.$message.error('删除公共配置失败！')
          this.$message.success('删除公共配置成功！')
          this.total -= 1
          if (this.total === (this.queryParams.p - 1) * this.queryParams.s && this.total !== 0) {
            this.queryParams.p -= 1
          }
          this.getConfigList()
        })
      }).catch(err => err)
    },
    // 监听size变化
    handleSizeChange (newSize) {
      this.queryParams.s = newSize
      this.getConfigList()
    },
    // 监听页码变化
    handleCurrentChange (newPage) {
      this.queryParams.p = newPage
      this.getConfigList()
    },
    // 表格样式
    cellStyle (data) {
      if (data.column.label === '公共配置名称') {
        return 'color: #409EFF'
      }
    }
  }
}
</script>

<style lang="less" scoped>
  /deep/ .el-dialog__body {
    padding: 20px 35px 10px 20px;
  }
  .el-row {
    margin: 10px 0;
  }
  .el-tabs {
    padding-left: 20px;
  }
</style>
